<?php
declare(strict_types=1);

namespace Core\HyperfUnit;

use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\Database\Model\Model;

class Result
{
    /**
     * 数据转响应对象
     * @param mixed $data
     * @return mixed
     */
    public static function toResponse(mixed $data): mixed
    {
        if (is_null($data) || is_string($data) || is_numeric($data) || is_bool($data)) {
            return $data;//已经是基本数据类型,直接返回原数据
        } elseif ($data instanceof LengthAwarePaginatorInterface) {
            return [
                'list' => self::toResponse($data->items()),
                'total' => $data->total(),//总页数
                'current' => $data->currentPage(),//当前页
                'size' => $data->perPage()
            ];
        } elseif (is_array($data)) {
            foreach ($data as $key => $value) {
                $data[$key] = self::toResponse($value);
            }
            return $data;
        } else if (is_object($data)) {
            if (in_array('toArray', get_class_methods($data)) || $data instanceof Model) {
                return self::toResponse($data->toArray());//可转换时转为数组
            }
        }
        return $data;
    }
}